<template>
  <el-link
    v-if="fileObject.url"
    type="primary"
    :underline="false"
    @click="preview"
    v-loading="loading"
    element-loading-custom-class="small-loading-icon"
  >
    {{ t('fileObjectDownload.buttonName') }}
  </el-link>
  <span v-else>{{ t('fileObjectDownload.noFile') }}</span>
</template>
<script lang="ts" setup>
import { FileRespVO } from '@/api/infra/file'
import { downloadFromS3 } from '@/utils/download'

defineOptions({ name: 'FileObjectDownload' })
const message = useMessage() // 消息弹窗

const { t } = useI18n() // 国际化

const props = defineProps({
  fileJson: {
    type: String,
    required: true
  }
})
const fileObject = ref<FileRespVO>({} as FileRespVO)
watchEffect(() => {
  try {
    fileObject.value = JSON.parse(props.fileJson ?? '{}')
  } catch {
    fileObject.value = {} as FileRespVO
  }
})

const loading = ref(false)
const preview = () => {
  loading.value = true
  fetch(fileObject.value.url)
    .then((response) => response.blob())
    .then((blob) => {
      if (blob.type === 'application/json') {
        message.error(t('fileObjectDownload.error'))
        return
      }
      const url = URL.createObjectURL(blob)
      window.open(url, '_blank')
    })
    .finally(() => {
      loading.value = false
    })
}

const downloadFile = () => {
  downloadFromS3(fileObject.value.url, fileObject.value.name)
}
</script>
